package com.solcoo.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.solcoo.dao.MenuDao;
import com.solcoo.json.MenuJson;
import com.solcoo.pojo.Menu;
import com.solcoo.util.FileUtil;
import com.solcoo.util.ImageUtil;

@Service
public class MenuService {

	private static final Logger logger = Logger.getLogger(MenuService.class);

	public static final String MENU_PATH = "static/pic/menu/";
	
	@Resource
	private MenuDao menuDao;
	
	
	public Map<String, Object> addMenu(Menu menu, Integer screenWidth, MultipartFile menuPic, HttpServletRequest request) throws Exception {
		// 图片
		if (menuPic == null || menuPic.isEmpty())
			return setFailInfo("图片不能为空");
		
		String name = menu.getName(); // 菜名
		if (name == null || "".equals(name.trim()))
			return setFailInfo("菜名不能为空");
		
		Double price = menu.getPrice(); // 价格
		if (price == null)
			return setFailInfo("价格不能为空");
		
		if (screenWidth == null)
			return setFailInfo("屏幕宽度不能为空");
		
		String picPath = request.getSession().getServletContext().getRealPath(MENU_PATH) + "/" + menu.getShanghuid();
		String picName = System.currentTimeMillis() + 
				menuPic.getOriginalFilename().substring(menuPic.getOriginalFilename().lastIndexOf("."));
		String picURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + MENU_PATH + menu.getShanghuid();
		
		menu.setPicPath(picPath); // 图片路径
		menu.setPicName(picName); // 图片名称
		menu.setPicURL(picURL); // 图片地址
		
		File picPathFile = new File(picPath);
		
		if (!picPathFile.exists())
			picPathFile.mkdirs(); // 创建菜单目录

		File picFile = new File(picPath + "/" + picName);
		
		byte[] bytes = menuPic.getBytes();
		boolean result = menuDao.addMenu(menu);
		if(!result) {
			return setFailInfo("菜单新增失败");
		}

		FileCopyUtils.copy(bytes, picFile); // 上传文件
		
		Map<String, Object> mm = this.listMenu(menu.getShanghuid(), null, "0", screenWidth, "1");

		ImageUtil.cutPicture(picPath, picName);
		
		int[] widths = {160, 240, 270, 320, 360, 400, 512, 640, 960};
		for(int width:widths) {
			ImageUtil iu = new ImageUtil(picPath, picName, width);
			new Thread(iu).start();
		}
		
		return mm;
	}
	
	
	public Map<String, Object> deleteMenu(Long id) throws Exception {
		boolean result = false;

		Menu menu = menuDao.getMenu(id);
		result = menuDao.deleteMenuById(id);

		if ( !result )
			return setFailInfo("菜单删除失败");
		
		FileUtil.deleteFile(menu.getPicPath(), menu.getPicName()); // 删除图片
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("result", true);
		map.put("msg", "菜单删除成功");
		
		return map;
	}
	
	
	public Map<String, Object> updateMenu(Menu menu) {
		boolean result = false;
		
		try {
			result = menuDao.updateMenu(menu);
		} catch (Exception e) {
			logger.error("系统异常", e);
			
			return setFailInfo("系统异常, 请重试！");
		}

		if ( !result )
			return setFailInfo("菜单修改失败");
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("result", true);
		map.put("msg", "菜单修改成功");
		
		return map;
	}
	
	
	public Map<String, Object> updateMenuPic(Long id, MultipartFile menuPic) throws Exception {
		if (menuPic == null || menuPic.isEmpty())
			return setFailInfo("图片不能为空");
		
		Menu menu = null;
		String picName = System.currentTimeMillis() + 
				menuPic.getOriginalFilename().substring(menuPic.getOriginalFilename().lastIndexOf("."));
		
		menu = menuDao.getMenu(id); 
	
		String oldPicName = menu.getPicName();
		menu.setPicName(picName); // 图片名称
		boolean result = menuDao.updateMenu(menu);
		
		FileUtil.deleteFile(menu.getPicPath(), oldPicName); // 删除图片
		
		byte[] bytes = menuPic.getBytes();
		File picFile = new File(menu.getPicPath() + "/" + picName);
		
		FileCopyUtils.copy(bytes, picFile); // 上传文件
			
			
		if ( !result )
			return setFailInfo("图片修改失败");

		ImageUtil.cutPicture(menu.getPicPath(), picName);

		int[] widths = {320, 160, 240, 270, 320, 360, 400, 512, 640, 960};
		for(int width:widths) {
			ImageUtil iu = new ImageUtil(menu.getPicPath(), picName, width);
			new Thread(iu).start();
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("result", true);
		map.put("msg", "图片修改成功");
		
		return map;
	}
	
	
	public Map<String, Object> getMenu(Long id) throws Exception {
		Menu menu = null;
		
		MenuJson menuJson = null;
		
		menu =  menuDao.getMenu(id);
		
		menuJson = new MenuJson();
		
		menuJson.setId(menu.getId());
		menuJson.setShanghuid(menu.getShanghuid());
		menuJson.setName(menu.getName());
		menuJson.setType(menu.getType());
		menuJson.setPrice(menu.getPrice());
		menuJson.setIsNew(menu.getIsNew());
		menuJson.setPicURL(menu.getPicURL() + "/" + menu.getPicName());
		menuJson.setRemark(menu.getRemark());
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("menu", menuJson);
		map.put("result", true);
		map.put("msg", "菜单获取成功");
		
		return map;	
	}
	
	
	public Map<String, Object> listMenu(Long shanghuid, String menuType, String sortType, 
			Integer screenWidth, String isShanghu) throws Exception {
		List<MenuJson> resultList = new ArrayList<MenuJson>();
		
		MenuJson menuJson = null;;
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("shanghuid", shanghuid);
		param.put("menuType", menuType);
		param.put("sortType", sortType);
		param.put("isShanghu", isShanghu);
		
		List<Menu> list = menuDao.getMenuListByShanghuid(param);
		
		Menu menu = null;
		
		String zoomURL = null;
		for (int i = 0; i < list.size(); i++) {
			menu = list.get(i);
			
			zoomURL = ImageUtil.zoomPicture(menu.getPicPath(), menu.getPicName(), screenWidth / 2);

			ImageUtil.cutPicture(menu.getPicPath(), menu.getPicName());
			
			menuJson = new MenuJson();
			
			menuJson.setId(menu.getId());
			menuJson.setShanghuid(menu.getShanghuid());
			menuJson.setName(menu.getName());
			menuJson.setType(menu.getType());
			menuJson.setPrice(menu.getPrice());
			menuJson.setIsNew(menu.getIsNew());
			menuJson.setPicURL(menu.getPicURL() + "/" + screenWidth / 2 + "/" + menu.getPicName());
			menuJson.setPicHeight(zoomURL);
			menuJson.setRemark(menu.getRemark());
			
			resultList.add(menuJson);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("menuList", resultList);
		map.put("result", true);
		map.put("msg", "菜单列表获取成功");
		
		return map;
	}
	
	/**
	 * 设置错误信息
	 * @param failInfo
	 * @return
	 */
	private Map<String, Object> setFailInfo(String failInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("result", false);
		map.put("failMsg", failInfo);
		
		return map;
	}
	
}